/**
 * Created by Forcs on 16/4/7.
 */
var co = require('co');

var LogRecycler = function (app, context) {
  var self = this;
  self.options = {
    year: null,
    month: null,
    date: null,
    dayOfWeek: null,
    hour: null,
    minute: null,
    second: null,
    logSources: []
  };
  self._handler = {};
  self.schedule = undefined;
  self.timeout = undefined;
};

LogRecycler.prototype.on = function (event, handler) {
  this._handler[event] = handler
};

LogRecycler.prototype.start = function () {
  var self = this;
  this.timeout = setTimeout(function () {
    self.recycle();
  }, 10 * 1000);
};

LogRecycler.prototype.recycle = function () {
  var self = this;
  co(function * () {
    var length = self.options.logSources.length;
    for (var i = 0; i < length; i++) {
      var item = self.options.logSources[i];

      var result = yield self._handler['handle-task'](item);
      if (self._handler['after-task']) {
        var next = yield self._handler['after-task'](item, result);
        if (!next) {
          break
        }
      }
    }
    self.timeout = setTimeout(function () {
      self.recycle();
    }, self.options.intervalSecond * 1000);
  }).catch(function (err) {
    if (self._handler['err']) {
      self._handler['err'] (err)
    }
    self.timeout = setTimeout(function () {
      self.recycle();
    }, self.options.intervalSecond * 1000);
  });
  if (self.timeout !== undefined) {
    clearTimeout(self.timeout);
    self.timeout = undefined;
  }
};

LogRecycler.prototype.stop = function () {
  var _self = this;
  if (_self.schedule) {
    _self.schedule.cancelNext()
  }
};


module.exports = LogRecycler;
